package com.tracelog.core.filter;

import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求体缓存过滤器
 * <p>用于捕获和缓存请求体和响应体，以便后续日志记录</p>
 *
 * @author tracelog
 * @since 1.0.0
 */
public class RequestBodyCacheFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        
        // 包装请求，缓存请求体
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        // 包装响应，缓存响应体
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        
        try {
            // 继续处理请求
            filterChain.doFilter(requestWrapper, responseWrapper);
        } finally {
            // 确保响应体内容被复制回原始响应
            responseWrapper.copyBodyToResponse();
        }
    }
} 